package cn.com.pajx.pajx_visitor_v3.ui.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.CheckBox;

import androidx.annotation.NonNull;

import com.google.zxing.BarcodeFormat;
import com.telpo.tps550.api.TelpoException;
import com.telpo.tps550.api.printer.UsbThermalPrinter;
import com.telpo.tps550.api.util.StringUtil;
import com.telpo.tps550.api.util.SystemUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.pajx.pajx_visitor_v3.R;
import cn.com.pajx.pajx_visitor_v3.api.Api;
import cn.com.pajx.pajx_visitor_v3.base.BaseMvpFragment;
import cn.com.pajx.pajx_visitor_v3.bean.EventMessage;
import cn.com.pajx.pajx_visitor_v3.bean.VisiteBean;
import cn.com.pajx.pajx_visitor_v3.mvp.presenter.LoadDataPresenterImpl;
import cn.com.pajx.pajx_visitor_v3.utils.AppConstant;
import cn.com.pajx.pajx_visitor_v3.utils.Base64Utils;
import cn.com.pajx.pajx_visitor_v3.utils.CommonUtil;
import cn.com.pajx.pajx_visitor_v3.utils.DateUtil;
import cn.com.pajx.pajx_visitor_v3.utils.LogUtils;
import cn.com.pajx.pajx_visitor_v3.utils.ToastUtil;

/**
 * 开始拜访的页面
 * create an instance of this fragment.
 */
@SuppressLint("NonConstantResourceId")
public class StartVisiteFragment extends BaseMvpFragment<LoadDataPresenterImpl> {

    @BindView(R.id.check_box_print)
    CheckBox checkBoxPrint;

    private final List<String> beans = new ArrayList<>();
    //打印机
    private UsbThermalPrinter mUsbThermalPrinter;
    private boolean lowBattery = false, no_paper = false;
    private String print_exception;
    private int deviceType;
    private final int NO_PAPER = 3, LOW_BATTERY = 4, PRINT_TICKET = 5, CANCEL_PROMPT = 6, PRINTERR = 7, OVER_HEAT = 8;
    private String printContent, qr_code, visite_id;

    @SuppressLint("HandlerLeak")
    private final Handler paperHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case NO_PAPER:
                    LogUtils.e("没有纸");
                    ToastUtil.toast("打印机缺纸");
                    speckChinese("打印机缺纸");
                    break;
                case LOW_BATTERY:
                    LogUtils.e("低电量");
                    ToastUtil.toast("打印机低电量");
                    speckChinese("打印机低电量");
                    break;
                case PRINT_TICKET:
                    new PrinterThread().start();
                    break;
                case CANCEL_PROMPT:
                    LogUtils.e("打印结束");
                    break;
                case OVER_HEAT:
                    ToastUtil.toast("打印机过热");
                    speckChinese("打印机过热");
                    LogUtils.e("打印机过热");
                    break;
                default:
                    speckChinese("打印机初始化失败");
                    LogUtils.e("Print Error!");
                    break;
            }
        }
    };

    public StartVisiteFragment() {
    }

    public static StartVisiteFragment newInstance(VisiteBean visiteBean) {
        StartVisiteFragment fragment = new StartVisiteFragment();
        Bundle args = new Bundle();
        args.putParcelable(AppConstant.VISITE_BEAN, visiteBean);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        registerPrintReceiver();
    }

    @Override
    protected void beforeInitHead() {
        super.beforeInitHead();
        VisiteBean bean = getArguments().getParcelable(AppConstant.VISITE_BEAN);
        if (bean != null) {
            visite_id = bean.getVis_id();
            handleQrcode();
            String visitor_name = AppConstant.VISITE_NAME + bean.getVis_name();
            String vinterviewee_name = AppConstant.INTERVIEWEE_NAME + bean.getUser_name();
            printContent = AppConstant.TICKET_TITLE + visitor_name + vinterviewee_name;
        }
    }

    /**
     * 处理二维码的字段
     */
    private void handleQrcode() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("vis_id", visite_id);
            qr_code = Base64Utils.base64Encode(jsonObject.toString());
            LogUtils.e("qr_code=" + qr_code);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_start_visite;
    }

    @Override
    protected LoadDataPresenterImpl initPresenter() {
        return new LoadDataPresenterImpl();
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        initUsbPrinter();
    }

    /**
     * 初始化打印机
     */
    private void initUsbPrinter() {
        mUsbThermalPrinter = new UsbThermalPrinter(mContext);
        deviceType = SystemUtil.getDeviceType();
        new Thread(() -> {
            try {
                mUsbThermalPrinter.start(0);//低速
                mUsbThermalPrinter.reset();
                LogUtils.e("version=" + mUsbThermalPrinter.getVersion());
            } catch (TelpoException e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 打印机广播监听
     */
    private void registerPrintReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction("android.intent.action.BATTERY_CAPACITY_EVENT");
        mContext.registerReceiver(printReceive, intentFilter);
    }

    @OnClick({R.id.iv_close, R.id.tv_cancel, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
            case R.id.tv_cancel:
                dismiss();
                break;
            case R.id.tv_confirm:
                startVisite();
                break;
        }

    }

    private void checkPrintTicket() {
        if (checkBoxPrint.isChecked()) {
            String visite_time = AppConstant.VISITE_TIME + DateUtil.getCurrentYMDHMS();
            printContent = printContent + visite_time;
            printTicket();
        }
    }

    /**
     * 开始拜访
     */
    private void startVisite() {
        LinkedHashMap<String, String> paramsMap = new LinkedHashMap<>();
        paramsMap.put("vis_id", visite_id);
        mPresenter.loadData(Api.VISITE_START, paramsMap, "VISITE_START", "");
    }

    /**
     * 打印小票
     */
    private void printTicket() {
        if (lowBattery) {
            paperHandler.sendMessage(paperHandler.obtainMessage(LOW_BATTERY, 1, 0, null));
        } else {
            if (!no_paper) {
                paperHandler.sendMessage(paperHandler.obtainMessage(PRINT_TICKET, 1, 0, null));
            } else {
                ToastUtil.toast("打印机初始化中");
                LogUtils.e("打印机初始化中");
            }
        }
    }

    private class PrinterThread extends Thread {

        public void run() {
            super.run();
            try {
                mUsbThermalPrinter.reset();
                mUsbThermalPrinter.searchMark(1, 1);
                mUsbThermalPrinter.setAlgin(UsbThermalPrinter.ALGIN_MIDDLE);
                mUsbThermalPrinter.setLineSpace(5);
                mUsbThermalPrinter.setBold(false);
                mUsbThermalPrinter.setTextSize(38);
                mUsbThermalPrinter.setGray(12);
                mUsbThermalPrinter.addString(printContent);
                mUsbThermalPrinter.printString();
                Bitmap bitmap = CommonUtil.encodeAsBitmap(qr_code, BarcodeFormat.QR_CODE, 340, 340);
                if (bitmap != null) {
                    mUsbThermalPrinter.printLogo(bitmap, true);
                }
                mUsbThermalPrinter.addString("请妥善保管小票，出门可扫小票上的二维码");
                mUsbThermalPrinter.printString();
                mUsbThermalPrinter.walkPaper(2);
                mUsbThermalPrinter.addString("签名区：");
                mUsbThermalPrinter.printString();
                mUsbThermalPrinter.walkPaper(30);
            } catch (Exception e) {
                e.printStackTrace();
                print_exception = e.toString();
                if (print_exception.equals("com.telpo.tps550.api.printer.NoPaperException")) {
                    no_paper = true;
                } else if (print_exception.equals("com.telpo.tps550.api.printer.OverHeatException")) {
                    paperHandler.sendMessage(paperHandler.obtainMessage(OVER_HEAT, 1, 0, null));
                } else {
                    paperHandler.sendMessage(paperHandler.obtainMessage(PRINTERR, 1, 0, null));
                }
            } finally {
                paperHandler.sendMessage(paperHandler.obtainMessage(CANCEL_PROMPT, 1, 0, null));
                if (no_paper) {
                    paperHandler.sendMessage(paperHandler.obtainMessage(NO_PAPER, 1, 0, null));
                    no_paper = false;
                }
            }
        }
    }

    private final BroadcastReceiver printReceive = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
                int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_NOT_CHARGING);
                int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
                int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
                // TPS390 can not print,while in low battery,whether is charging or not charging
                if (deviceType == StringUtil.DeviceModelEnum.TPS390.ordinal()) {
                    lowBattery = level * 5 <= scale;
                } else {
                    if (status != BatteryManager.BATTERY_STATUS_CHARGING) {
                        lowBattery = level * 5 <= scale;
                    } else {
                        lowBattery = false;
                    }
                }
            } else if (action.equals("android.intent.action.BATTERY_CAPACITY_EVENT")) {// Only use for TPS550MTK devices
                int status = intent.getIntExtra("action", 0);
                int level = intent.getIntExtra("level", 0);
                if (status == 0) {
                    lowBattery = level < 1;
                } else {
                    lowBattery = false;
                }
            }
        }
    };

    @Override
    public void onSuccess(String data, String aesKey, String message, int code, String tag) {
        super.onSuccess(data, aesKey, message, code, tag);
        checkPrintTicket();
        dismiss();
        //关闭预约界面
        EventBus.getDefault().post(new EventMessage(AppConstant.VISITE_START));
        skip2Success("1");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mContext.unregisterReceiver(printReceive);
    }
}